package com.jin.concurrent.example.syncContainer;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Vector;

/**
 * @author JinLiu
 */
@Slf4j
public class VectorExample1 {

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();

        vector.add(1);
        vector.add(2);
        vector.add(3);

//        test1(vector); // ConcurrentModificationException
//        test2(vector); // ConcurrentModificationException
        test3(vector); // success
    }

    private static void test1(Vector<Integer> vector) {
        for (Integer integer : vector) {
            if (integer.equals(3)) {
                vector.remove(integer);
            }
        }
    }

    private static void test2(Vector<Integer> vector) {
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next.equals(3)) {
                vector.remove(next);
            }
        }
    }

    private static void test3(Vector<Integer> vector) {
        for (int i = 0; i < vector.size(); i++) {
            if (vector.get(i).equals(3)) {
                vector.remove(i);
            }
        }

        log.info("{}", JSON.toJSONString(vector));
    }

}
